﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace WpfApp1
{
    public class FindInk
    {

        /// <summary>
        /// 获得指定盘符下的所有指定类型的文件路径
        /// </summary>
        /// <param name="path">所有的文件夹路径</param>
        /// <param name="FilePath">获取的文件路径集合</param>
        /// <param name="FileName">指定的文件后缀</param>
        public void GetFolderAndFile(string[] path, List<string> FilePath, string FileName)
        {
            foreach (string str in path)
            {
                string[] Next = Directory.GetDirectories(str); //获取当前路径下的所有文件夹
                string[] Files = Directory.GetFiles(str, FileName);
                foreach (string file in Files)
                    FilePath.Add(file);
                GetFolderAndFile(Next, FilePath, FileName);
            }
        }

        /// <summary>
        /// 获取指定后缀名字文件
        /// </summary>
        /// <param name="path">根目录 D:\\</param>
        /// <param name="pattern">.exe</param>
        /// <param name="filePathCollector"></param>
        /// <returns></returns>
        public IEnumerable<string> RecursiveFileSearch(string path, string pattern, ICollection<string> filePathCollector = null)
        {
            try
            {
                filePathCollector = filePathCollector ?? new LinkedList<string>();

                var matchingFilePaths = Directory.GetFiles(path, pattern);

                foreach (var matchingFile in matchingFilePaths)
                {

                    filePathCollector.Add(matchingFile);
                }

                var subDirectories = Directory.EnumerateDirectories(path);

                foreach (var subDirectory in subDirectories)
                {
                    RecursiveFileSearch(subDirectory, pattern, filePathCollector);
                }

                return filePathCollector;
            }
            catch (Exception error)
            {
                bool isIgnorableError = error is PathTooLongException ||
                    error is UnauthorizedAccessException;

                if (isIgnorableError)
                {
                    return Enumerable.Empty<string>();
                }
               
                throw error;
            }
        }

    }
}
